package com.fx.zmlzml.controller;

import com.fx.zmlzml.common.response.Result;
import com.fx.zmlzml.entity.PcPowerSupply;
import com.fx.zmlzml.exception.BusinessException;
import com.fx.zmlzml.exception.ErrorEnum;
import com.fx.zmlzml.service.PcPowerSupplyService;
import com.fx.zmlzml.util.MessageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 电脑电源Controller
 * 提供RESTful API接口，用于操作电脑电源数据
 */
@RestController
@RequestMapping("/api/powerSupply")
@Tag(name = "电脑电源管理", description = "提供电脑电源的CRUD操作及相关查询功能")
public class PcPowerSupplyController {
    
    private static final Logger logger = LoggerFactory.getLogger(PcPowerSupplyController.class);
    
    @Autowired
    private PcPowerSupplyService pcPowerSupplyService;
    
    /**
     * 分页查询电脑电源列表
     */
    @GetMapping("/list")
    @Operation(summary = "分页查询电脑电源列表", description = "分页查询电脑电源信息，支持排序和筛选")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PageInfo<PcPowerSupply>> getPcPowerSuppliesByPage(
            @Parameter(description = "页码，默认为1", example = "1", required = false) @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页条数，默认为15", example = "15", required = false) @RequestParam(defaultValue = "15") Integer pageSize) {
        logger.info("分页查询电脑电源列表请求，页码：{}，每页条数：{}", pageNum, pageSize);
        try {
            // 参数校验
            if (pageNum < 1 || pageSize < 1) {
                throw new BusinessException(ErrorEnum.PARAM_INVALID,
                        MessageUtils.getMessage("common.validation.page_num") + "，" + 
                        MessageUtils.getMessage("common.validation.page_size"));
            }

            PageHelper.startPage(pageNum, pageSize);
            List<PcPowerSupply> list = pcPowerSupplyService.list();
            PageInfo<PcPowerSupply> pageInfo = new PageInfo<>(list);

            logger.debug("分页查询电脑电源成功，总条数：{}", pageInfo.getTotal());
            return Result.i18nSuccess(pageInfo, "case.query.success", null);
        } catch (Exception e) {
            logger.error("分页查询电脑电源失败", e);
            return Result.error(MessageUtils.getMessage("query.failed"));
        }
    }

    /**
     * 根据ID查询电脑电源
     */
    @GetMapping("/{id}")
    @Operation(summary = "根据ID查询电脑电源", description = "根据主键ID查询电脑电源详细信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到资源", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "查询失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<PcPowerSupply> getPcPowerSupplyById(
            @Parameter(description = "电脑电源ID") @PathVariable Long id) {
        logger.info("根据ID查询电脑电源请求，ID：{}", id);
        try {
            PcPowerSupply powerSupply = pcPowerSupplyService.getById(id);
            if (powerSupply == null) {
                logger.warn("未找到电脑电源，ID：{}", id);
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND);
            }
            logger.debug("根据ID查询电脑电源成功，ID：{}", id);
            return Result.success(powerSupply);
        } catch (BusinessException e) {
            logger.warn("根据ID查询电脑电源业务异常：{}", e.getMessage());
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("根据ID查询电脑电源失败，ID：{}", id, e);
            return Result.error(MessageUtils.getMessage("query.failed"));
        }
    }
    
    /**
     * 添加电脑电源
     */
    @PostMapping
    @Operation(summary = "添加电脑电源", description = "添加新的电脑电源信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "添加成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "添加失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> addPcPowerSupply(
            @Parameter(description = "电脑电源信息") @RequestBody PcPowerSupply powerSupply) {
        logger.info("添加电脑电源请求，制造商：{}", powerSupply.getManufacturer());
        try {
            powerSupply.setCreatedTime(new Date());
            powerSupply.setUpdatedTime(new Date());
            boolean result = pcPowerSupplyService.save(powerSupply);
            if (result) {
                logger.debug("添加电脑电源成功，ID：{}", powerSupply.getId());
                return Result.success(result);
            } else {
                logger.warn("添加电脑电源失败，制造商：{}", powerSupply.getManufacturer());
                return Result.error(MessageUtils.getMessage("save.failed"));
            }
        } catch (Exception e) {
            logger.error("添加电脑电源失败，制造商：{}", powerSupply.getManufacturer(), e);
            return Result.error(MessageUtils.getMessage("save.failed"));
        }
    }
    
    /**
     * 更新电脑电源
     */
    @PutMapping
    @Operation(summary = "更新电脑电源", description = "更新电脑电源信息")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到资源", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "更新失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> updatePcPowerSupply(
            @Parameter(description = "电脑电源信息") @RequestBody PcPowerSupply powerSupply) {
        logger.info("更新电脑电源请求，ID：{}", powerSupply.getId());
        try {
            // 检查是否存在
            // 检查是否存在
            if (pcPowerSupplyService.getById(powerSupply.getId()) == null) {
                logger.warn("更新电脑电源时未找到该电源，ID：{}", powerSupply.getId());
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND);
            }
            powerSupply.setUpdatedTime(new Date());
            boolean result = pcPowerSupplyService.updateById(powerSupply);
            if (result) {
                logger.debug("更新电脑电源成功，ID：{}", powerSupply.getId());
                return Result.success(result);
            } else {
                logger.warn("更新电脑电源失败，ID：{}", powerSupply.getId());
                return Result.error(MessageUtils.getMessage("update.failed"));
            }
        } catch (BusinessException e) {
            logger.warn("更新电脑电源业务异常：{}", e.getMessage());
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("更新电脑电源失败，ID：{}", powerSupply.getId(), e);
            return Result.error(MessageUtils.getMessage("update.failed"));
        }
    }
    
    /**
     * 删除电脑电源
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除电脑电源", description = "根据ID删除电脑电源")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "404", description = "未找到资源", content = @Content(schema = @Schema(implementation = Result.class))),
            @ApiResponse(responseCode = "500", description = "删除失败", content = @Content(schema = @Schema(implementation = Result.class)))
    })
    public Result<Boolean> deletePcPowerSupply(
            @Parameter(description = "电脑电源ID") @PathVariable Long id) {
        logger.info("删除电脑电源请求，ID：{}", id);
        try {
            // 检查是否存在
            if (pcPowerSupplyService.getById(id) == null) {
                logger.warn("删除电脑电源时未找到该电源，ID：{}", id);
                throw new BusinessException(ErrorEnum.RESOURCE_NOT_FOUND);
            }
            boolean result = pcPowerSupplyService.removeById(id);
            if (result) {
                logger.debug("删除电脑电源成功，ID：{}", id);
                return Result.success(result);
            } else {
                logger.warn("删除电脑电源失败，ID：{}", id);
                return Result.error(MessageUtils.getMessage("delete.failed"));
            }
        } catch (BusinessException e) {
            logger.warn("删除电脑电源业务异常：{}", e.getMessage());
            return Result.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("删除电脑电源失败，ID：{}", id, e);
            return Result.error(MessageUtils.getMessage("delete.failed"));
        }
    }
}